import React, { useState } from 'react';
import { CodeArea, Switch } from 'choerodon-ui/pro';

// 这两个主题不是组件内置的主题，需要手动引入
import 'codemirror/theme/material.css';
import 'codemirror/theme/idea.css';

// 引入格式化器，注意使用模块的默认导出
import YAMLFormatter from 'choerodon-ui/pro/lib/code-area/formatters/YAMLFormatter';
// 引入 yaml lint
import 'choerodon-ui/pro/lib/code-area/lint/yaml';
// 处理 codemirror 的SSR问题， 如无需SSR，请用import代替require;
if (typeof window !== 'undefined') {
  // 提供对应语言的语法高亮
  require('codemirror/mode/yaml/yaml');
}


const yamlText = `YAML:
  - A human-readable data serialization language
  - https://en.wikipedia.org/wiki/YAML
yaml:
  - A complete JavaScript implementation
  - https://www.npmjs.com/package/yaml
`;

const yamlStyle = { height: 200 };

const codeAreaControlled: React.FC = () => {
  const [theme, setTheme] = useState('idea');
  const [text, setText] = useState(yamlText);

  const handleThemeChange = async () => {
    if (theme === 'material') {
      setTheme('idea');
    } else {
      setTheme('material');
    }
  };

  const handleChange = async (value: string) => {
    setText(value);
  };

  return (
    <div>
      <h4>yaml</h4>
      <CodeArea
        value={text}
        name="content"
        options={{ mode: 'yaml', theme }}
        style={yamlStyle}
        formatter={YAMLFormatter}
        onChange={handleChange}
      />
      <Switch onChange={handleThemeChange} unCheckedChildren="idea">material</Switch>
    </div>
  );
};
export default codeAreaControlled;